package com.app.config;


import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.json.JSONUtil;
import com.app.common.Api;
import com.app.config.annotation.NoWrapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.Objects;

@RestControllerAdvice
public class ResponseConfig implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        Class<?> declaringClass = returnType.getDeclaringClass();
        Method method = returnType.getMethod();
        return !AnnotationUtil.hasAnnotation(declaringClass, NoWrapper.class)
                && !AnnotationUtil.hasAnnotation(method, NoWrapper.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (Objects.equals(String.class, returnType.getGenericParameterType())) {
            response.getHeaders().add("content-type", "application/json");
            return JSONUtil.toJsonStr(Api.ok(body));
        }
        return body instanceof Api ? body : Api.ok(body);
    }
}
